/*
 * main.cpp
 *
 *  Created on: Jun 21, 2011
 *      Author: blyth
 */

#include <DataReader.h>
#include <TApplication.h>
#include <TH2D.h>
#include <TColor.h>
#include <TCanvas.h>
#include <signal.h>
#include <stdlib.h>
#include <iostream>
using namespace std;

TApplication* app;

void TCanvas::Closed() {
	Emit("Closed()");

	gApplication->Terminate(0);
}

int main(int argc, char** argv) {
	int argcFake = 0;
	app = new TApplication("adsf", &argcFake, argv);

	DataReader* dr = new DataReader(argv[1], atoi(argv[2]), true);
	double* sum;
	int** data = dr->GetData(atoi(argv[3]), sum);

	int crystal = -1;
	if (argc > 4)
		crystal = atoi(argv[4]);

	Double_t r[5] = { 1, 1, 0, 0, 0 };
	Double_t g[5] = { 0, 1, 1, 1, 0 };
	Double_t b[5] = { 0, 0, 0, 1, 1 };
	Double_t stop[5] = { 0, .25, .5, .75, 1 };
	TColor::CreateGradientColorTable(5, stop, r, g, b, 20);
	TH1I* littleHisto = NULL;
	TH2D* bigHisto = new TH2D("bigHisto", "Whole Detector View", 72, -900, 900, 72, -900, 900);

	for (int i = 0; i < 2716; i++) {
		if (data[i] == NULL)
			continue;
		int x = data[i][48];
		int y = data[i][49];
		int ped = data[i][50];
		double energy = sum[i];
		bigHisto->Fill(x, y, energy);
		if (i > 2239) {
			bigHisto->Fill(x - 1, y, energy);
			bigHisto->Fill(x, y - 1, energy);
			bigHisto->Fill(x - 1, y - 1, energy);
		}
		if (energy > 0)
			cout << i << "\t" << energy << endl;
		if (i == crystal) {
			cout << "Crystal: " << i << "\tEnergy (MeV): " << energy << "\tPedestal: " << ped << "\tX pos: " << x
					<< "\tY pos: " << y << endl;
			littleHisto = new TH1I("littleHisto", "Single Channel View", 48, -0.5, 47.5);
			for (int j = 0; j < 48; j++) {
				littleHisto->Fill(j, data[i][j]);
			}
		}

		delete[] data[i];
	}

	delete[] data;
	delete[] sum;

	TCanvas* bigHistoCanvas = new TCanvas("bigHistoCanvas");
	bigHisto->Draw("lego2");
	if (littleHisto) {
		TCanvas* littleHistoCanvas = new TCanvas("littleHistoCanvas");
		littleHisto->Draw();
	}
	app->Run(true);

	delete dr;
	app->Delete();
	return 0;
}
